<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
// 导入消息工具
import message from "@/utils/message.js";
// 导入图标工具
import { ArrowLeft, Plus, Delete, Check, DocumentCopy } from "@/utils/icons.js";
import { getResumeDetail, createResume, updateResume } from "@/api/resume";
// 使用自定义的简化接口，避免类型错误
interface ResumeItem {
    id: string;
    title: string;
    name: string;
    gender: string;
    birth_date: string;
    phone: string;
    email: string;
    highest_education: string;
    target_position: string;
    expected_salary: string;
    job_status: string;
    self_evaluation: string;
    avatar: string;
    status: string;
    update_time: string;
    education_experience: any[];
    work_experience: any[];
    project_experience: any[];
    skills: string[];
    certificates: any[];
    portfolios: any[];
    [key: string]: any;
}

const router = useRouter();
const route = useRoute();
const store = useStore();

// 判断是新建还是编辑模式
const isEdit = computed(() => route.query.edit === "true");
const isNew = computed(() => !route.query.id);
const resumeId = computed(() => route.query.id as string);

// 页面标题
const pageTitle = computed(() => {
    if (isNew.value) return "创建简历";
    if (isEdit.value) return "编辑简历";
    return "简历详情";
});

// 表单数据
const resumeForm = reactive<ResumeItem>({
    id: "",
    title: "",
    name: "",
    gender: "",
    birth_date: "",
    phone: "",
    email: "",
    highest_education: "",
    target_position: "",
    expected_salary: "",
    job_status: "0", // 0-在职，1-离职，2-应届生
    self_evaluation: "",
    avatar: "",
    status: "",
    update_time: "",

    // 教育经历
    education_experience: [],

    // 工作经历
    work_experience: [],

    // 项目经验
    project_experience: [],

    // 技能特长
    skills: [],

    // 证书
    certificates: [],

    // 作品展示
    portfolios: [],
});

// 教育水平选项
const educationOptions = [
    { value: "高中", label: "高中" },
    { value: "专科", label: "专科" },
    { value: "本科", label: "本科" },
    { value: "硕士", label: "硕士" },
    { value: "博士", label: "博士" },
    { value: "其他", label: "其他" },
];

// 在职状态选项
const jobStatusOptions = [
    { value: "0", label: "在职" },
    { value: "1", label: "离职" },
    { value: "2", label: "应届生" },
];

// 表单校验规则
const rules = reactive({
    title: [{ required: true, message: "请输入简历标题", trigger: "blur" }],
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    phone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" },
    ],
    email: [
        { required: true, message: "请输入邮箱地址", trigger: "blur" },
        { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
    ],
    highest_education: [{ required: true, message: "请选择最高学历", trigger: "change" }],
});

// 使用泛型指定ref类型
const formRef = ref<any>(null);
const loading = ref(false);

// 技能输入相关变量
const inputValue = ref("");
const inputVisible = ref(false);
const inputSkill = ref<any>(null);

// 可能需要添加切换输入框显示的方法
const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
        if (inputSkill.value) {
            inputSkill.value.focus();
        }
    });
};

// 获取简历详情
const getResumeData = async () => {
    if (isNew.value) return;

    loading.value = true;
    try {
        let response: any = { code: 0, data: null };
        if (resumeId.value) {
            try {
                // 尝试从API获取数据
                response = await getResumeDetail(resumeId.value);
            } catch (apiError) {
                console.error("API获取简历详情失败", apiError);
                // 如果API调用失败，尝试从store获取或使用模拟数据
                const mockResume = {
                    id: resumeId.value,
                    title: "模拟简历数据",
                    name: "测试用户",
                    status: "1",
                    // 其他必要字段...
                };
                response = { code: 200, data: mockResume };
            }
        } else {
            // 如果没有传递ID，则使用模拟数据
            const mockResume = {
                id: "mock-" + Date.now(),
                title: "新建简历",
                name: "",
                status: "0",
                // 其他必要字段...
            };
            response = { code: 200, data: mockResume };
        }

        if ((response.code === 200 || response.code === 0) && response.data) {
            // 填充表单数据
            Object.assign(resumeForm, response.data);

            // 确保数组字段存在
            resumeForm.education_experience = resumeForm.education_experience || [];
            resumeForm.work_experience = resumeForm.work_experience || [];
            resumeForm.project_experience = resumeForm.project_experience || [];
            resumeForm.skills = resumeForm.skills || [];
            resumeForm.certificates = resumeForm.certificates || [];
            resumeForm.portfolios = resumeForm.portfolios || [];
        } else {
            message.error("获取简历数据失败");
            setTimeout(() => router.back(), 1500);
        }
    } catch (error) {
        console.error("获取简历数据错误", error);
        message.error("获取简历数据失败");
        setTimeout(() => router.back(), 1500);
    } finally {
        loading.value = false;
    }
};

// 保存简历
const saveResume = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();

        loading.value = true;
        let response;

        if (isNew.value) {
            response = await createResume(resumeForm);
        } else {
            response = await updateResume(resumeForm);
        }

        if (response.code === 200 || response.code === 0) {
            message.success(isNew.value ? "创建简历成功" : "更新简历成功");
            if (isNew.value) {
                // 创建成功后跳转到编辑页面
                router.replace({
                    path: "/user/resumeInfo",
                    query: { id: response.data.id, edit: "true" },
                });
            } else if (!isEdit.value) {
                // 在查看模式下保存后，刷新数据
                getResumeData();
            }
        } else {
            message.error(response.message || "保存失败");
        }
    } catch (error) {
        console.error("保存简历错误", error);
        message.error("表单验证失败或提交过程中出错");
    } finally {
        loading.value = false;
    }
};

// 添加教育经历
const addEducation = () => {
    resumeForm.education_experience.push({
        id: Date.now().toString(),
        school_name: "",
        major: "",
        degree: "",
        start_date: "",
        end_date: "",
        description: "",
    });
};

// 删除教育经历
const removeEducation = (index: number) => {
    resumeForm.education_experience.splice(index, 1);
};

// 添加工作经历
const addWorkExperience = () => {
    resumeForm.work_experience.push({
        id: Date.now().toString(),
        company_name: "",
        position: "",
        start_date: "",
        end_date: "",
        description: "",
    });
};

// 删除工作经历
const removeWorkExperience = (index: number) => {
    resumeForm.work_experience.splice(index, 1);
};

// 添加项目经验
const addProjectExperience = () => {
    resumeForm.project_experience.push({
        id: Date.now().toString(),
        project_name: "",
        role: "",
        start_date: "",
        end_date: "",
        description: "",
    });
};

// 删除项目经验
const removeProjectExperience = (index: number) => {
    resumeForm.project_experience.splice(index, 1);
};

// 添加技能
const addSkill = (skill: string) => {
    if (skill && !resumeForm.skills.includes(skill)) {
        resumeForm.skills.push(skill);
    }
};

// 移除技能
const removeSkill = (skill: string) => {
    const index = resumeForm.skills.indexOf(skill);
    if (index > -1) {
        resumeForm.skills.splice(index, 1);
    }
};

// 返回列表页
const goBack = () => {
    router.push({
        path: "/user/resume",
    });
};

// 切换到编辑模式
const switchToEdit = () => {
    router.replace({
        path: "/user/resumeInfo",
        query: { id: resumeId.value, edit: "true" },
    });
};

// 复制简历
const duplicateResume = async () => {
    loading.value = true;
    try {
        // 复制当前简历数据，并修改标题为"复制 - 原标题"
        const duplicatedResume = {
            ...resumeForm,
            id: "",
            title: `复制 - ${resumeForm.title}`,
        };

        const response = await createResume(duplicatedResume);
        if (response.code === 200 || response.code === 0) {
            message.success("复制简历成功");
            router.replace({
                path: "/user/resumeInfo",
                query: { id: response.data.id, edit: "true" },
            });
        } else {
            message.error(response.message || "复制简历失败");
        }
    } catch (error) {
        console.error("复制简历错误", error);
        message.error("复制简历失败");
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    getResumeData();
});
</script>

<template>
    <div class="resume-info-container" v-loading="loading">
        <div class="page-header">
            <div class="left">
                <el-button link @click="goBack" :icon="ArrowLeft">返回</el-button>
                <h2>{{ pageTitle }}</h2>
            </div>
            <div class="actions">
                <template v-if="isEdit || isNew">
                    <el-button type="primary" @click="saveResume" :icon="Check">保存简历</el-button>
                </template>
                <template v-else>
                    <el-button type="primary" @click="switchToEdit">编辑简历</el-button>
                    <el-button type="info" @click="duplicateResume" :icon="DocumentCopy">复制简历</el-button>
                </template>
            </div>
        </div>

        <el-form
            ref="formRef"
            :model="resumeForm"
            :rules="rules"
            label-width="120px"
            class="resume-form"
            :disabled="!(isEdit || isNew)"
        >
            <!-- 基本信息 -->
            <el-card class="form-section">
                <template #header>
                    <div class="card-header">
                        <h3>基本信息</h3>
                        <span class="header-tip">填写基本个人信息</span>
                    </div>
                </template>

                <el-row :gutter="20">
                    <el-col :xs="24" :sm="12">
                        <el-form-item label="简历标题" prop="title">
                            <el-input v-model="resumeForm.title" placeholder="例如：前端开发工程师-姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :xs="24" :sm="8">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="resumeForm.name" placeholder="请输入姓名" />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="8">
                        <el-form-item label="性别">
                            <el-radio-group v-model="resumeForm.gender">
                                <el-radio label="男">男</el-radio>
                                <el-radio label="女">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="8">
                        <el-form-item label="出生日期">
                            <el-date-picker
                                v-model="resumeForm.birth_date"
                                type="date"
                                placeholder="选择日期"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :xs="24" :sm="12">
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="resumeForm.phone" placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="12">
                        <el-form-item label="电子邮箱" prop="email">
                            <el-input v-model="resumeForm.email" placeholder="请输入电子邮箱" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :xs="24" :sm="8">
                        <el-form-item label="最高学历" prop="highest_education">
                            <el-select v-model="resumeForm.highest_education" placeholder="请选择" style="width: 100%">
                                <el-option
                                    v-for="item in educationOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="8">
                        <el-form-item label="求职状态">
                            <el-select v-model="resumeForm.job_status" placeholder="请选择" style="width: 100%">
                                <el-option
                                    v-for="item in jobStatusOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :xs="24" :sm="8">
                        <el-form-item label="期望薪资">
                            <el-input v-model="resumeForm.expected_salary" placeholder="例如：10k-15k" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="目标职位">
                    <el-input v-model="resumeForm.target_position" placeholder="例如：前端开发工程师" />
                </el-form-item>

                <el-form-item label="自我评价">
                    <el-input
                        v-model="resumeForm.self_evaluation"
                        type="textarea"
                        :rows="4"
                        placeholder="简要介绍自己的优势和特长"
                    />
                </el-form-item>
            </el-card>

            <!-- 教育经历 -->
            <el-card class="form-section">
                <template #header>
                    <div class="card-header">
                        <h3>教育经历</h3>
                        <span class="header-tip">填写你的学习经历</span>
                        <el-button
                            v-if="isEdit || isNew"
                            type="primary"
                            plain
                            :icon="Plus"
                            @click="addEducation"
                            class="add-btn"
                        >
                            添加教育经历
                        </el-button>
                    </div>
                </template>

                <div v-for="(edu, index) in resumeForm.education_experience" :key="edu.id" class="experience-item">
                    <div class="item-header">
                        <h4>教育经历 {{ index + 1 }}</h4>
                        <el-button
                            v-if="isEdit || isNew"
                            type="danger"
                            :icon="Delete"
                            circle
                            @click="removeEducation(index)"
                            class="delete-btn"
                        />
                    </div>

                    <el-row :gutter="20">
                        <el-col :xs="24" :sm="12">
                            <el-form-item :label="'学校名称'" :prop="`education_experience.${index}.school_name`">
                                <el-input v-model="edu.school_name" placeholder="请输入学校名称" />
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="12">
                            <el-form-item :label="'专业'" :prop="`education_experience.${index}.major`">
                                <el-input v-model="edu.major" placeholder="请输入专业名称" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :xs="24" :sm="8">
                            <el-form-item :label="'学历'" :prop="`education_experience.${index}.degree`">
                                <el-select v-model="edu.degree" placeholder="请选择" style="width: 100%">
                                    <el-option
                                        v-for="item in educationOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="16">
                            <el-form-item :label="'起止时间'">
                                <el-date-picker
                                    v-model="edu.start_date"
                                    type="month"
                                    placeholder="开始时间"
                                    format="YYYY-MM"
                                    value-format="YYYY-MM"
                                    style="width: 45%"
                                />
                                <span class="date-separator">至</span>
                                <el-date-picker
                                    v-model="edu.end_date"
                                    type="month"
                                    placeholder="结束时间"
                                    format="YYYY-MM"
                                    value-format="YYYY-MM"
                                    style="width: 45%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item :label="'在校经历'">
                        <el-input
                            v-model="edu.description"
                            type="textarea"
                            :rows="3"
                            placeholder="描述你的主要课程、学生工作、获奖情况等"
                        />
                    </el-form-item>

                    <el-divider v-if="index < resumeForm.education_experience.length - 1" />
                </div>

                <el-empty v-if="resumeForm.education_experience.length === 0" description="暂无教育经历信息">
                    <el-button v-if="isEdit || isNew" type="primary" @click="addEducation">添加教育经历</el-button>
                </el-empty>
            </el-card>

            <!-- 工作经历 -->
            <el-card class="form-section">
                <template #header>
                    <div class="card-header">
                        <h3>工作经历</h3>
                        <span class="header-tip">填写你的工作经验</span>
                        <el-button
                            v-if="isEdit || isNew"
                            type="primary"
                            plain
                            :icon="Plus"
                            @click="addWorkExperience"
                            class="add-btn"
                        >
                            添加工作经历
                        </el-button>
                    </div>
                </template>

                <div v-for="(work, index) in resumeForm.work_experience" :key="work.id" class="experience-item">
                    <div class="item-header">
                        <h4>工作经历 {{ index + 1 }}</h4>
                        <el-button
                            v-if="isEdit || isNew"
                            type="danger"
                            :icon="Delete"
                            circle
                            @click="removeWorkExperience(index)"
                            class="delete-btn"
                        />
                    </div>

                    <el-row :gutter="20">
                        <el-col :xs="24" :sm="12">
                            <el-form-item :label="'公司名称'" :prop="`work_experience.${index}.company_name`">
                                <el-input v-model="work.company_name" placeholder="请输入公司名称" />
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="12">
                            <el-form-item :label="'职位'" :prop="`work_experience.${index}.position`">
                                <el-input v-model="work.position" placeholder="请输入职位名称" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item :label="'起止时间'">
                        <el-date-picker
                            v-model="work.start_date"
                            type="month"
                            placeholder="开始时间"
                            format="YYYY-MM"
                            value-format="YYYY-MM"
                            style="width: 45%; max-width: 200px"
                        />
                        <span class="date-separator">至</span>
                        <el-date-picker
                            v-model="work.end_date"
                            type="month"
                            placeholder="结束时间"
                            format="YYYY-MM"
                            value-format="YYYY-MM"
                            style="width: 45%; max-width: 200px"
                        />
                    </el-form-item>

                    <el-form-item :label="'工作内容'">
                        <el-input
                            v-model="work.description"
                            type="textarea"
                            :rows="4"
                            placeholder="描述你的工作职责、成就和贡献"
                        />
                    </el-form-item>

                    <el-divider v-if="index < resumeForm.work_experience.length - 1" />
                </div>

                <el-empty v-if="resumeForm.work_experience.length === 0" description="暂无工作经历信息">
                    <el-button v-if="isEdit || isNew" type="primary" @click="addWorkExperience">添加工作经历</el-button>
                </el-empty>
            </el-card>

            <!-- 项目经验 -->
            <el-card class="form-section">
                <template #header>
                    <div class="card-header">
                        <h3>项目经验</h3>
                        <span class="header-tip">填写你参与的项目</span>
                        <el-button
                            v-if="isEdit || isNew"
                            type="primary"
                            plain
                            :icon="Plus"
                            @click="addProjectExperience"
                            class="add-btn"
                        >
                            添加项目经验
                        </el-button>
                    </div>
                </template>

                <div
                    v-for="(project, index) in resumeForm.project_experience"
                    :key="project.id"
                    class="experience-item"
                >
                    <div class="item-header">
                        <h4>项目经验 {{ index + 1 }}</h4>
                        <el-button
                            v-if="isEdit || isNew"
                            type="danger"
                            :icon="Delete"
                            circle
                            @click="removeProjectExperience(index)"
                            class="delete-btn"
                        />
                    </div>

                    <el-row :gutter="20">
                        <el-col :xs="24" :sm="12">
                            <el-form-item :label="'项目名称'" :prop="`project_experience.${index}.project_name`">
                                <el-input v-model="project.project_name" placeholder="请输入项目名称" />
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="12">
                            <el-form-item :label="'担任角色'" :prop="`project_experience.${index}.role`">
                                <el-input v-model="project.role" placeholder="例如：前端开发工程师" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item :label="'起止时间'">
                        <el-date-picker
                            v-model="project.start_date"
                            type="month"
                            placeholder="开始时间"
                            format="YYYY-MM"
                            value-format="YYYY-MM"
                            style="width: 45%; max-width: 200px"
                        />
                        <span class="date-separator">至</span>
                        <el-date-picker
                            v-model="project.end_date"
                            type="month"
                            placeholder="结束时间"
                            format="YYYY-MM"
                            value-format="YYYY-MM"
                            style="width: 45%; max-width: 200px"
                        />
                    </el-form-item>

                    <el-form-item :label="'项目描述'">
                        <el-input
                            v-model="project.description"
                            type="textarea"
                            :rows="4"
                            placeholder="描述项目的背景、你的职责以及成果"
                        />
                    </el-form-item>

                    <el-divider v-if="index < resumeForm.project_experience.length - 1" />
                </div>

                <el-empty v-if="resumeForm.project_experience.length === 0" description="暂无项目经验信息">
                    <el-button v-if="isEdit || isNew" type="primary" @click="addProjectExperience"
                        >添加项目经验</el-button
                    >
                </el-empty>
            </el-card>

            <!-- 技能特长 -->
            <el-card class="form-section">
                <template #header>
                    <div class="card-header">
                        <h3>技能特长</h3>
                        <span class="header-tip">添加你的专业技能和特长</span>
                    </div>
                </template>

                <el-form-item label="技能标签">
                    <div class="skills-container">
                        <el-tag
                            v-for="skill in resumeForm.skills"
                            :key="skill"
                            :disable-transitions="false"
                            @close="removeSkill(skill)"
                            :closable="isEdit || isNew"
                        >
                            {{ skill }}
                        </el-tag>

                        <el-input
                            v-if="isEdit || isNew"
                            class="input-new-tag"
                            v-model="inputValue"
                            ref="inputSkill"
                            size="small"
                            @keyup.enter.native="
                                addSkill(inputValue);
                                inputValue = '';
                            "
                            @blur="
                                addSkill(inputValue);
                                inputValue = '';
                            "
                            placeholder="输入技能并按Enter添加"
                        />

                        <el-button
                            v-if="(isEdit || isNew) && !inputVisible"
                            class="button-new-tag"
                            size="small"
                            @click="showInput"
                        >
                            + 添加技能
                        </el-button>
                    </div>
                </el-form-item>
            </el-card>

            <!-- 表单底部操作区 -->
            <div class="form-actions">
                <el-button @click="goBack">返回</el-button>
                <el-button v-if="isEdit || isNew" type="primary" @click="saveResume" :loading="loading"
                    >保存简历</el-button
                >
            </div>
        </el-form>
    </div>
</template>

<style scoped>
.resume-info-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header .left {
    display: flex;
    align-items: center;
}

.page-header h2 {
    margin: 0 0 0 10px;
}

.form-section {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    align-items: center;
}

.card-header h3 {
    margin: 0;
}

.header-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 14px;
}

.add-btn {
    margin-left: auto;
}

.experience-item {
    position: relative;
    margin-bottom: 20px;
}

.item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.item-header h4 {
    margin: 0;
}

.date-separator {
    margin: 0 10px;
}

.delete-btn {
    flex-shrink: 0;
}

.form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

.skills-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.skill-tag {
    margin-right: 0;
}

.input-new-tag,
.button-new-tag {
    margin-right: 0;
}

@media screen and (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .page-header .actions {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }
}
</style>
